<template>
	<view class="u-p-l-40 u-p-r-40">
		<u-form :model="form" ref="uForm" :error-type="errorType">
			<u-form-item label="用户昵称" prop="name" label-width="180">
				<u-input v-model="form.name" />
			</u-form-item>
			<u-form-item label="手机号码" prop="phone" label-width="180">
				<u-input placeholder="请输入手机号" v-model="form.phone" type="number"></u-input>
			</u-form-item>
			<u-form-item label="手机验证码" prop="code" label-width="180">
				<u-input placeholder="请输入验证码" v-model="code" type="text"></u-input>
				<u-button slot="right" type="success" size="mini" @click="getPhoneCode">获取验证码</u-button>
			</u-form-item>
			<u-form-item label="邮箱账号" prop="email" label-width="180">
				<u-input placeholder="请输入邮箱" v-model="form.email" type="email"></u-input>
			</u-form-item>
			<u-form-item label="邮箱验证码" prop="emailcode" label-width="180">
				<u-input placeholder="请输入验证码" v-model="emailCode" type="text"></u-input>
				<u-button slot="right" type="success" size="mini" @click="getEmailCode">获取验证码</u-button>
			</u-form-item>
		</u-form>
		<u-button @click="submit">提交</u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				errorType: ['message'],
				form: {
					name: '',
					phone: '',
					email: ''
				},
				code: '',
				emailCode: '',
				rules: {
					name: [{
						required: true,
						message: '请输入昵称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}]
				}
			}
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(async (valid) => {
					if (valid) {
						// 更新用户信息
						await this.$u.api.userInfoUpdata(this.form)
						// 更新手机号
						if(this.form.phone && this.code){
							const params = {
								code:this.code,
								phone:this.form.phone
							}
							await this.$u.api.phone(params)
						}
						// 更新邮箱
						if(this.form.email && this.emailCode){
							const params = {
								code:this.emailCode,
								email:this.form.email
							}
							await this.$u.api.email(params)
						}
						// 重刷新用户信息并将数据更新vuex_user
						this.$u.utils.updataUser()
						this.$u.toast('更新成功')
					}
				});
			},
			async getPhoneCode() {
				const params = {
					phone:this.form.phone
				}
				const res = await this.$u.api.phoneCode(params)
			},
			async getEmailCode() {
				const params = {
					email:this.form.email
				}
				const res = await this.$u.api.emailCode(params)
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.form.name = this.vuex_user.name
		}
	}
</script>

<style lang="scss" scoped>
	
</style>
